<?php

namespace common\logics;

use Yii;
use common\models\freight\FreightMode;
use common\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%freight_mode}}".
 *
 * @property int $id
 * @property string $template_id 隶属模版ID
 * @property int $type 货运方式
 * @property string $parent_id
 * @property string $area_code
 * @property int $quantity 默认数量
 * @property string $price 默认运费
 * @property int $increase_quantity 每增加数量
 * @property string $increase_price 增加运费
 */
class OrderFreightLogic extends \common\models\shop\ShopOrderGoods {

    public $sum = 0;
    public $template_id = 0;

    public static function calac($id, $area = null) {
        $data = static::find()
        ->alias('t')
        ->joinWith('product product', true)
        ->where(['t.order_id' => $id])
        ->select(['product.template_id', 'sum(t.goods_number) as sum'])
        ->groupBy('product.template_id')
        ->all();

        $array = ArrayHelper::map($data, 'template_id', 'sum');

        $modes = FreightMode::find()
        ->alias('t')
        ->with('areas')
        ->joinWith('areas area', TRUE)
        ->where([
            't.template_id' => array_keys($array),
        ])->andFilterWhere([
            'or',
            ['area.code' => $area],
            ['t.parent_id' => 0],
        ])
        ->orderBy([
            't.template_id' => SORT_ASC,
            't.parent_id' => SORT_DESC,
        ])
        ->groupBy('t.template_id')
        ->all();

        $price = 0;
        foreach ($modes as $m) {
            $num = ArrayHelper::getValue($array, $m->template_id, 0);
            if ($num > 0) {
                $price += $m->price;
            }
            $num -= $m->quantity;
            if ($num > 0) {
                $xn = ceil($num / $m->increase_quantity);
                if ($xn) {
                    $price += $xn * $m->increase_price;
                }
            }
        }
        return $price;
    }

}
